package beanstao.util.memcache;

import com.alisoft.xplatform.asf.cache.memcached.client.MemCachedClient;
import com.alisoft.xplatform.asf.cache.memcached.client.SockIOPool;

public class CacheService
{
	String cacheServerList;

	String cacheServerWeights;

	boolean cacheCluster = false;

	int initialConnections = 10;

	int minSpareConnections = 5;

	int maxSpareConnections = 50;

	long maxIdleTime = 1000 * 60 * 30; // 30 minutes

	long maxBusyTime = 1000 * 60 * 5; // 5 minutes

	long maintThreadSleep = 1000 * 5; // 5 seconds

	int socketTimeOut = 1000 * 3; // 3 seconds to block on reads

	int socketConnectTO = 1000 * 3; // 3 seconds to block on initial
	// connections. If 0, then will use blocking
	// connect (default)

	boolean failover = false; // turn off auto-failover in event of server
	// down

	boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
	// pool

	MemCachedClient mc;

	public CacheService()
	{
		mc = new MemCachedClient();
		mc.setCompressEnable(false);
	}

	/**
	 * 放入
	 * 
	 */
	public void put(String key, Object obj)
	{
		mc.set(key, obj);
	}

	/**
	 * 删除
	 */
	public void remove(String key)
	{
		mc.delete(key);
	}

	/**
	 * 获取
	 */
	public Object get(String key)
	{
		return mc.get(key);
	}

	/**
	 * 判断是否存在
	 */
	public boolean isExist(String key)
	{
		return mc.keyExists(key);
	}

	@SuppressWarnings("unused")
	private void init()
	{
		String[] serverlist = { "127.0.0.1:11211" };
		Integer[] weights = { 3 };
		// initialize the pool for memcache servers
		SockIOPool pool = SockIOPool.getInstance();
		pool.setServers(serverlist);
		pool.setWeights(weights);
		pool.setInitConn(initialConnections);
		pool.setMinConn(minSpareConnections);
		pool.setMaxConn(maxSpareConnections);
		pool.setMaxIdle(maxIdleTime);
		pool.setMaxBusyTime(maxBusyTime);
		pool.setMaintSleep(maintThreadSleep);
		pool.setSocketTO(socketTimeOut);
		pool.setSocketConnectTO(socketConnectTO);
		pool.setNagle(nagleAlg);
		pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
		pool.initialize();
		System.out.println("CacheService.init():  初始化memcached pool!");
	}

	@SuppressWarnings("unused")
	private void destory()
	{
		SockIOPool.getInstance().shutDown();
	}
}
